/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

    //
//  BAAbstractViewController.m
//  redia-bapps-ios
//
//  Created by Brian Vestergaard Danielsen on 10/10/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BAAbstractViewController.h"
#import "BAUtils.h"
#import "BAUserSearchViewController.h"
#import "BALibrarySettings.h"
#import "BAPatronSettings.h"
#import "BAWebBrowserViewController.h"

@interface BAAbstractViewController ()

@property (weak, nonatomic) IBOutlet UILabel *noAbstractLabel;
@property (weak, nonatomic) IBOutlet UIWebView *abstractWebView;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *loadingContentIndicator;

@property (weak, nonatomic) IBOutlet UILabel *yearTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *yearLabel;
@property (weak, nonatomic) IBOutlet UILabel *shelfMarkTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *shelMarkLabel;
@property (weak, nonatomic) IBOutlet UILabel *languageTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *languageLabel;
@property (weak, nonatomic) IBOutlet UIView *bottomDetailsView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomDetailsHeightConstraint;

@end

@implementation BAAbstractViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    BA_LABEL_SET_FONT_MEDIUM(self.noAbstractLabel);

    if (RD_IS_IPAD) {
        BA_LABEL_SET_FONT_LIGHT_WITH_SIZE(self.yearTitleLabel,11);
        BA_LABEL_SET_FONT_REGULAR_WITH_SIZE(self.yearLabel,13);
        BA_LABEL_SET_FONT_LIGHT_WITH_SIZE(self.shelfMarkTitleLabel,11);
        BA_LABEL_SET_FONT_REGULAR_WITH_SIZE(self.shelMarkLabel,13);
        BA_LABEL_SET_FONT_LIGHT_WITH_SIZE(self.languageTitleLabel,11);
        BA_LABEL_SET_FONT_REGULAR_WITH_SIZE(self.languageLabel,13);
        
    } else {
        BA_LABEL_SET_FONT_LIGHT(self.yearTitleLabel);
        BA_LABEL_SET_FONT_REGULAR(self.yearLabel);
        BA_LABEL_SET_FONT_LIGHT(self.shelfMarkTitleLabel);
        BA_LABEL_SET_FONT_REGULAR(self.shelMarkLabel);
        BA_LABEL_SET_FONT_LIGHT(self.languageTitleLabel);
        BA_LABEL_SET_FONT_REGULAR(self.languageLabel);
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setFullRecord:(BAFullRecord*)record
{
    fullRecord = record;
    
    NSString* abstract = fullRecord.abstract;
    if (abstract==nil) {
        abstract=@"";
    }
    abstract = [abstract stringByReplacingOccurrencesOfString:@"\n" withString:@"<br />"];
    
    if ([fullRecord.seriesInfo length]>0) {
        abstract = [NSString stringWithFormat:@"%@<br /><br />%@",fullRecord.seriesInfo,abstract];
    }
    [self setAbstract:abstract];
    
    if (! [[BAPatronSettings instance] isUserAllowedLibrarianAccessForCurrentLibrary]) {
        //only show bottom details when not librarian mode
        
        self.bottomDetailsView.hidden=NO;
        self.yearLabel.text = fullRecord.year;
        self.shelMarkLabel.text = fullRecord.shelfmark;
        self.languageLabel.text = fullRecord.language;
    } else {
        self.bottomDetailsHeightConstraint.constant=0;
        self.bottomDetailsView.hidden=NO;
    }
    
}

- (void)setAbstract:(NSString*)abstract
{
    NSMutableString* abstractAsHtml = [NSMutableString new];
    bool includeTags = [BALibrarySettings instance].isImfEnabled || [[BAPatronSettings instance] isUserAllowedLibrarianAccessForCurrentLibrary];
    if(abstract.length == 0) {
        if (includeTags) {
            if ([fullRecord.subjects count]==0) {
                [self.noAbstractLabel setHidden:NO];
            }
        } else {
            [self.noAbstractLabel setHidden:NO];
        }
    }
    
    if (RD_IS_IPAD) {
        if ([[BAPatronSettings instance] isUserAllowedLibrarianAccessForCurrentLibrary]) {
            [abstractAsHtml appendString:[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"BAAbstractViewTemplate_iPadLibrarian" ofType:@"html"] encoding:NSUTF8StringEncoding error:nil]];
        } else {
            [abstractAsHtml appendString:[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"BAAbstractViewTemplate_iPad" ofType:@"html"] encoding:NSUTF8StringEncoding error:nil]];
        }
    } else {
        [abstractAsHtml appendString:[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"BAAbstractViewTemplate_iPhone" ofType:@"html"] encoding:NSUTF8StringEncoding error:nil]];
    }
    
    [abstractAsHtml appendFormat:@"<p>%@</p>",abstract];
    
    if (includeTags) {
        for (NSString* s in fullRecord.subjects) {
            [abstractAsHtml appendString:[NSString stringWithFormat:@"<div class=\"subjectButton\"> <a href=\"bappssubject://search/%1$@\">  %1$@ </a> </div> ", s]];
        }
        
    }
    
    [abstractAsHtml appendString:@"<div id=\"end\"></div></body></html>"];
    
    [self.abstractWebView loadHTMLString:abstractAsHtml baseURL:nil];
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self.loadingContentIndicator stopAnimating];
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL* url = [request URL];
    NSString* scheme = [url scheme];
    if ([scheme isEqualToString:@"bappssubject"]) {
        NSString* subjectsearch = [url path];
        if ([subjectsearch length]>2) {
            subjectsearch = [subjectsearch substringFromIndex:1];
            DLog(@"subject: %@",subjectsearch);
            BAUserSearchViewController* search = [BAUserSearchViewController new];
            [self.navigationController pushViewController:search animated:YES];
            [search externalPerformSearchWithSearchString:subjectsearch withLibrarianFilters:@{}];

        }
        return NO;
    } else if (navigationType == UIWebViewNavigationTypeLinkClicked && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"])) {
        BAWebBrowserViewController* webBrowser = [BAWebBrowserViewController new];
        [webBrowser setUrl:request.URL.absoluteString];
        [self.navigationController presentViewController:webBrowser animated:YES completion:nil];
        return NO;
    }
    
    
    return YES;
}

/* dep?
- (void) receiveAbstractLoadingDone:(NSNotification*) notification
{
    DLog(@"receiveAbstractLoadingDone");
}
*/

@end
